//
//  SIOAuthViewController.swift
//  SinaImiate
//
//  Created by xiaoming on 16/7/2.
//  Copyright © 2016年 GoodJob. All rights reserved.
//

import UIKit
import SVProgressHUD


class SIOAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
    
    override func loadView() {
        
        view = webView
        
        view.backgroundColor = UIColor.white()
        
        webView.delegate = self
        
        webView.scrollView.isScrollEnabled = false
        
        title = "登录新浪微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(back), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoSubmit))
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(SIAppleKey)&redirect_uri=\(SIRedirectURI)"
        
        guard let url = URL(string: urlString) else {
            return
        }
        
        let request = URLRequest(url: url)
        
        webView.loadRequest(request)
    }
    
    //MARK: -监听方法
    @objc private func back() {
        
        SVProgressHUD.dismiss()
        
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func autoSubmit() {
        
        let js = "document.getElementById('userId').value = '18943105260';" + "document.getElementById('passwd').value = 'huamingming1992';"
        
        webView.stringByEvaluatingJavaScript(from: js)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }

}

// MARK: - UIWebViewDelegate
extension SIOAuthViewController: UIWebViewDelegate {
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //MARK: -请求的前缀如果不是自己写的回调网址,那么加载页面
        if request.url?.absoluteString?.hasPrefix(SIRedirectURI) == false {
            
            return true
        }
        //MARK: - 回调的地址中如果有code那么授权成功
         if request.url?.query?.hasPrefix("code=") == false {
            
            print("授权失败")
            back()
            
            return false
        }
        //MARK: -到这里request.url.query里面肯定有code= "xxx"
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        print("授权码" + "\(code)")
        
        SINetworkTools.shared.loadAccessToken(code: code) { (isSuccess) in
            
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "网络请求不给通过")
            } else {
//                SVProgressHUD.showInfo(withStatus: "登录通过")
                
                ///发送通知,不关心哪个控制器监听,告诉应用程序需要跳转
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: userLoginSuccessedNotification), object: nil)
                
                self.back()
            }
            
        }
        
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
